<template>
  <el-form ref="form" label-width="80px" :model="formData" :rules="rules">
    <el-form-item label="选择产品" prop="productId">
      <el-select v-model="formData.productId" filterable placeholder="请选择" :disabled="!!product">
        <el-option
          v-for="item in productList"
          :key="item.productId"
          :label="item.name"
          :value="item.id">
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="数量" prop="amount">
      <el-input-number v-model="formData.amount" placeholder="请输入数量" :min="1" controls-position="right" />
    </el-form-item>
    <el-form-item label="导出价格">
      <el-input-number v-model="formData.exportPrice" placeholder="请输入导出价格" 
        :precision="2" :min="0" controls-position="right"></el-input-number>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="save" size="small" :loading="saving">保存</el-button>
      <el-button @click="cancel(false)" size="small">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import {productEnableAll} from '@/api/product'
import {redeemCodeAdd} from '@/api/redeemCode';

export default {
  name: 'RedeemForm',
  props: ['product'],
  data() {
    return {
      productList:  this.product ? [this.product] : [],
      formData: {
        productId: this.product ? this.product.productId : '',
        amount: '',
        exportPrice: ''
      },
      rules: {
        productId: [
          {type: 'number', required: true, messsage: '请选择产品'}
        ],
        amount: [
          {type: 'number', required: true, messsage: '请输入数量'}
        ],
        exportPrice: [
          {type: 'number', required: true, messsage: '请输入导出价格'}
        ]
      },
      saving: false
    }
  },
  methods: {
    async requestProductAll() {
      try{
        const {data} = await productEnableAll();
        this.productList = data;
      } catch(err) {
        console.log(err);
      }
    },
    save() {
      this.$refs.form.validate(async(valid) => {
        if (!valid) {
          return;
        }
        try {
          this.saving = true;
          await redeemCodeAdd(this.formData)
          this.$message.success('生成成功');
          this.saving = false;
          this.cancel(true);
        } catch(err) {
          this.saving = false;
        }
      })
    },
    cancel(isRefresh = true) {
      this.$emit('cancel', isRefresh)
    }
  },
  created() {
    if (!this.product) {
      this.requestProductAll();
    }
  },
}
</script>

<style>

</style>